#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/24 22:28
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : view_sms_template.py
# @Software: PyCharm
# @Desc    :
import json

from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework.generics import GenericAPIView

from ssms import models
from common.utils.pagination import EnhancedPageNumberPagination
from common.utils.rsp import success_response, error_response
from ssms.filters.filter_sms_template import SMSTemplateFilter
from ssms.models import SMSTemplate, SMSLog
from ssms.sers.ser_sms_template import SMSTemplateSerializer
from ssms.utils.util_aliyun import AliYunSMS


class SMSTemplateListCreateView(GenericAPIView):
    """
    SMSTemplate列表查询 + 新增接口
    - GET: 分页查询短信模板列表
    - POST: 新增短信模板
    """
    queryset = SMSTemplate.objects.filter(is_delete=0, pt_flag=0)
    serializer_class = SMSTemplateSerializer
    pagination_class = EnhancedPageNumberPagination
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_class = SMSTemplateFilter
    ordering_fields = ["create_time", "sort_num", "name"]

    # ordering = ["-sort_num", "-create_time"]

    def get(self, request):
        """查询短信模板列表"""
        filtered_qs = self.filter_queryset(self.get_queryset())
        page_qs = self.paginate_queryset(filtered_qs)
        serializer = self.get_serializer(page_qs, many=True)
        paginated_data = self.paginator.get_paginated_response(serializer.data).data
        return success_response(data=paginated_data, message="短信模板列表查询成功")

    def post(self, request):
        """新增短信模板"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return success_response(
            data=serializer.data,
            message=f"短信模板「{serializer.validated_data['name']}」创建成功"
        )


class SMSTemplateRetrieveUpdateDestroyView(GenericAPIView):
    """
    SMSTemplate单条操作接口
    - GET: 查询单个模板详情
    - PUT/PATCH: 更新模板
    - DELETE: 逻辑删除模板
    - POST: 发送短信（额外扩展接口）
    """
    queryset = SMSTemplate.objects.all()
    serializer_class = SMSTemplateSerializer
    lookup_field = "pk"

    def get_object(self):
        """获取有效模板（未删除+非压测）"""
        instance = super().get_object()
        if instance.is_delete == 1 or instance.pt_flag == 1:
            raise ValueError("短信模板不存在或已被删除")
        return instance

    def get(self, request, pk):
        """查询单个模板详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return success_response(data=serializer.data, message="短信模板详情查询成功")

    def put(self, request, pk):
        """全量更新模板"""
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=False)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return success_response(data=serializer.data, message=f"模板「{instance.name}」更新成功")

    def patch(self, request, pk):
        """部分更新模板"""
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return success_response(data=serializer.data, message=f"模板「{instance.name}」部分更新成功")

    def delete(self, request, pk):
        """逻辑删除模板"""
        instance = self.get_object()
        instance.is_delete = 1
        instance.save()
        return success_response(message=f"模板「{instance.name}」已删除", data=None)

    def post(self, request, pk):
        """
        扩展接口：使用当前模板发送短信并记录日志
        请求参数：{"phone": "13800138000", "template_param": {"code": "123456"}, "out_id": ""}
        """
        try:
            # 1. 获取模板和参数
            instance = self.get_object()
            phone = request.data.get("phone")
            template_param = request.data.get("template_param", {})
            out_id = request.data.get("out_id", "")

            # 2. 参数校验
            if not phone:
                return error_response(message="手机号不能为空", code=400)
            if not template_param:
                return error_response(message="模板变量不能为空", code=400)

            # 3. 获取供应商配置（阿里云AK/SK）
            provider = instance.sms_provider
            if not provider.sms_key or not provider.sms_secret:
                return error_response(message=f"供应商「{provider.sms_name}」未配置API密钥", code=400)

            # 4. 调用阿里云短信接口发送
            sms_client = AliYunSMS(sms_key=provider.sms_key, sms_secret=provider.sms_secret)
            result = sms_client.send_sms(
                mobile=phone,
                sign_name=instance.sign,
                template_code=instance.template_id,
                template_param=template_param,
                out_id=out_id
            )

            # 5. 记录短信发送日志
            sms_log = SMSLog.objects.create(
                phone=phone,
                sign=instance.sign,
                template_id=instance.template_id,
                content=f"模板：{instance.name}，参数：{json.dumps(template_param)}",
                is_send=1 if result["success"] else 0
            )

            # 6. 返回结果
            if result["success"]:
                return success_response(
                    data={"log_id": sms_log.id, "request_id": result["request_id"]},
                    message="短信发送成功"
                )
            else:
                return error_response(
                    data={"log_id": sms_log.id, "message": result["message"]},
                    message="短信发送失败",
                    code=500
                )

        except Exception as e:
            return error_response(message=f"发送失败：{str(e)}", code=500)


class SMSTemplateTestSendView(GenericAPIView):
    def post(self, request, pk):
        request_body = request.data
        print(f'request_body: {request_body}')
        sms_template = models.SMSTemplate.objects.get(pk=pk)
        sign_name = sms_template.sign
        template_id = sms_template.template_id
        mobile = request_body.get("phone")
        content = request_body.get("test_data", {})
        sms = AliYunSMS(sms_key=sms_template.sms_provider.sms_key, sms_secret=sms_template.sms_provider.sms_secret)
        result = sms.send_sms(
            mobile=mobile,
            sign_name=sign_name,
            template_code=template_id,
            template_param=content
        )
        print('单条发送结果:', result)
        ret_success = result.get("success", "")
        message = result.get('message', "")

        sms_content = f"模板ID：{template_id}，发送内容：{content}" if ret_success else message
        SMSLog.objects.create(
            phone=mobile,
            sign=sign_name,
            template_id=template_id,
            content=sms_content,
            is_send=1 if result["success"] else 0
        )
        return success_response(success=result.get("success"), message=f"{result.get('message')}", data="")
